package one.stand.service.impl;

import com.jmp.autocofiguration.util.OssUtil2;
import com.jmp.base.dto.DynamicCommentSaveVo;
import com.jmp.base.dto.MessagePushRequest;
import com.jmp.base.dto.MessagePushType;
import com.jmp.feign.MessageFeign;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.dto.UserDto;
import one.stand.mapper.CommentMapperExt;
import one.stand.mapper.DynamicMapperExt;
import one.stand.model.Comment;
import one.stand.model.Dynamic;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.DynamicService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @author cjr
 */
@Slf4j
@Service
public class DynamicServiceImpl implements DynamicService {
    @Autowired
    private MessageFeign messageFeign;

    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;

    @Autowired
    private DynamicMapperExt dynamicMapperExt;
    @Autowired
    private CommentMapperExt commentMapperExt;

    @Override
    public void addDynamicInfo(Dynamic model) {
//        if (DynamicApi.TYPE_DYNAMIC == model.getType()) {
//            User user = userAdminService.getByUserId(model.getCreateUserId());
//            AssertUtil.isTrue(user.getRoleId() > 0, "你不是企业管理员，无法操作！");
//        }
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        AssertUtil.isTrue(companyBaseService.isByLabel(optUser.getCompanyId(), CompanyBaseService.LABEL_DYNAMIC), ResultEnum.PARAM_CHECK, "您当前还没有红木圈发布权限");

        AssertUtil.nonNull(model.getTitle(), ResultEnum.PARAM_CHECK, "请输入想要发的动态内容");
        AssertUtil.isTrue(model.getTitle().length() <= 128, ResultEnum.PARAM_CHECK, "动态内容不能超过128字");

        model.setPhotos(OssUtil2.getWebsiteUrlReplace(model.getPhotos()));
        model.setDetails(OssUtil2.getWebsiteUrlReplace(model.getDetails()));

        if (model.getDynamicId() == null) {

            if (Objects.nonNull(model.getRelateType())) {
                Dynamic dynamic = dynamicMapperExt.selectRelate(model.getCreateUserId(), model.getRelateType(), model.getRelateId());
                if (Objects.nonNull(dynamic)) {
                    log.warn("用户（{}）已创建（{} {}）动态，不用再创建", model.getCreateUserId(), model.getRelateType(), model.getRelateId());
                    return;
                }
            }
            model.setCreateTime(new Date());
            model.setIsDel(0);
            int r = dynamicMapperExt.insertSelective(model);
            AssertUtil.isTrue(r > 0, ResultEnum.FAIL);
        } else {
            model.setCompanyId(null);
            model.setCreateTime(null);
            model.setCreateUserId(null);
            int r = dynamicMapperExt.updateByPrimaryKeySelective(model);
            AssertUtil.isTrue(r > 0, ResultEnum.FAIL);
        }
    }

    @Override
    public void delDynamicInfo(Integer id, Integer userId) {
        Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(id);
        AssertUtil.isTrue(dynamic.getCreateUserId().equals(userId)
                || userAdminService.get(userId).isAdminUser(), ResultEnum.PARAM_CHECK, "你不是发布人，无法操作！");

        Dynamic model = new Dynamic();
        model.setDynamicId(id);
        model.setIsDel(1);
        int r = dynamicMapperExt.updateByPrimaryKeySelective(model);
        AssertUtil.isTrue(r > 0, ResultEnum.FAIL);
    }

    @Override
    public void deleteByRelate(Integer relateType, Integer relateId) {
        dynamicMapperExt.deleteByRelate(relateType, relateId);
    }

    @Override
    public void updateByRelate(Integer relateType, Integer relateId, Dynamic dynamic) {

        dynamic.setPhotos(OssUtil2.getWebsiteUrlReplace(dynamic.getPhotos()));
        dynamic.setDetails(OssUtil2.getWebsiteUrlReplace(dynamic.getDetails()));

        dynamicMapperExt.updateByRelate(relateType, relateId, dynamic.getTitle(), dynamic.getDetails(), dynamic.getPhotos());
    }

    @Override
    @Transactional
    public DynamicCommentSaveVo commentSave(Integer commentType, Integer dynamicId, Integer parentId, Integer userId, String text, Integer cardId) {
        Comment model = new Comment();
        Comment commentParent = null;
        if (Objects.nonNull(parentId)) {
            commentParent = commentMapperExt.selectByPrimaryKey(parentId);
            model.setRootId(commentParent.getRootId() == 0 ? commentParent.getCommentId() : commentParent.getRootId());
            model.setParentId(parentId);
            model.setCoverUserId(commentParent.getUserId());
            commentType = commentParent.getCommentType();
            dynamicId = commentParent.getDynamicId();
        }
        model.setCommentType(commentType);
        model.setDynamicId(dynamicId);
        model.setUserId(userId);
        model.setText(text);
        model.setCardId(cardId);//入口cardId
        model.setCreateTime(new Date());
        model.setIsDel(0);
        commentMapperExt.insertSelective(model);

        // 咨询回复通推送提醒
        UserDto user = userAdminService.get(userId);
        Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(dynamicId);
        String[] fillData = {user.getName(), DateUtil.getDay(), text};
        MessagePushRequest pushRequest = MessagePushRequest.builder()
                .type(MessagePushType.COMMENT_REPLY)
                .toId(dynamic.getCreateUserId())
                .fillData(fillData)
                .pageParams(new Object[]{dynamicId})
                .build();
        messageFeign.push(pushRequest);

        return DynamicCommentSaveVo.builder()
                .commentId(model.getCommentId())
                .userId(model.getUserId())
                .coverUserId(model.getCoverUserId())
                .build();
    }

    @Override
    public void commentRemove(Integer commentId, Integer userId) {
        Comment model = commentMapperExt.selectByPrimaryKey(commentId);
        AssertUtil.isTrue(Objects.nonNull(model) && model.getUserId().equals(userId), "只能删除自己的评论！");

        Comment modelRemove = new Comment();
        modelRemove.setCommentId(commentId);
        modelRemove.setIsDel(1);
        commentMapperExt.updateByPrimaryKeySelective(modelRemove);
    }

    @Override
    public void commentThumbs(Integer commentId, Boolean thumbsFlag) {
        commentMapperExt.updateThumbs(commentId, thumbsFlag ? 1 : -1);
    }
}
